#课堂练习

#文件名称
fileName='notes.txt'

#打开和读取文件
def ReadFile(fileName):
    my_file=open(fileName,'r')
    lines=my_file.readlines()
    my_file.close()
    print(lines)

print('\n一次性读取完文件所有内容')
ReadFile('notes.txt')

#一行一行的读取文件
def ReadPerLine(filename):
    myfile=open(filename,'r')
    curRowInfo = myfile.readline()
    while curRowInfo:
        print(curRowInfo,end='')
        curRowInfo = myfile.readline()
    myfile.close()

print('\n一行一行的读取文件')
ReadPerLine('notes.txt')

#读取二进制文件
def ReadBinary(fileName):
    binary=open(fileName,'rb')
    info=binary.readlines()
    print(info)
    binary.close()
#读取.wav文件
print('\n读取.wav文件')
ReadBinary('splat.wav')


#文件操作(追加文件)
import datetime
def AppendInfo(filename,needAddInfo):
    file=open(filename,'a')
    t=datetime.datetime.now()
    file.write('\n'+str(t)+needAddInfo)
    file.close()
    print('追加内容:',needAddInfo,' 到文件：',fileName,' 完成')
print('\n文件操作（追加文件）')
AppendInfo(fileName,'测试添加的信息')
print('\n追加文件后读取文件内容如下：')
ReadFile(fileName)


#文件操作（写文件[会覆盖原有内容]）
def WriteInfo(fileName):
    file=open(fileName,'w')
    t=datetime.datetime.now()
    strTime=str(t)
    file.write(strTime+' Eat supper\n')
    file.write(strTime+' Play soccer\n')
    file.write(strTime+' Go to bed')
    file.close()

fileName2='writeFile.txt'
print('\n文件操作（写文件）')
WriteInfo(fileName2)
ReadFile(fileName2)
WriteInfo(fileName2)
ReadFile(fileName2)

#在文件中保存pickle
import pickle

#保存对象
def SaveObj(needSaveObj,fileName):
    picklefile=open(fileName,'wb')
    pickle.dump(needSaveObj,picklefile)
    picklefile.close()
    print('保存',needSaveObj,' 到 ',fileName,' 完成')

print('\n在文件中保存pickle')
mylist=['Fred',73,'Hello There',81.9876e-13]
pickleFile='mypickleList.pk'
SaveObj(mylist,pickleFile)


def LoadObj(fileName):
    pickleFile=open(fileName,'rb')
    recoverdList=pickle.load(pickleFile)
    pickleFile.close()
    print('解析：',fileName,' 文件的内容是：',recoverdList)
    return recoverdList

LoadObj(pickleFile)










